package freebase;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.io.*;

public class InsertArticleMeta {
	public static void main(String[] args) {
		try {
			Connection conn;
			Statement stmt;
			//ResultSet res;

			Class.forName("com.mysql.jdbc.Driver").newInstance();

			conn = DriverManager.getConnection(
					"jdbc:mysql://pardosa06.cs.washington.edu/freebase",
					"clzhang", "wiki");

			stmt = conn.createStatement();

//			res = stmt
//					.executeQuery("select MAX(wpid) AS MAXID from articlesMeta");
//			int maxid = -1;
//			while (res.next()) {
//				String maxidstr = res.getString("MAXID");
//				if(maxidstr!=null){
//					maxid = Integer.parseInt(maxidstr);
//				}
//			}
//			res.close();

			BufferedReader br = new BufferedReader(new FileReader(args[0]));
			String line = "";
			int ln = 1;
			int inserted = 0;
			while ((line = br.readLine()) != null) {
//				if (ln <= maxid) {
//					ln++;
//					continue;
//				}
				try {
					//line = line.replaceAll("'","''");
					String[] abc = line.split("\t");
					String wpid = abc[0];
					String name = abc[1].replaceAll("'","''");
					ResultSet res = stmt.executeQuery("select wpid from articlesMeta where wpid="+wpid);
					if(res.next()){
						continue;
					}
					String query = "insert into articlesMeta values (";
					query+=wpid+","+"'"+name+"')";
					stmt.executeUpdate(query);
					ln++;
					inserted++;
					if(inserted%100000==0)System.out.print(".");
					if(inserted%10000000==0)System.out.println();
				} catch (Exception e) {
					System.err.println(e.toString());
				}
			}

			br.close();
		} catch (Exception ex) {
			System.out.println("Error : " + ex.toString());
		}

	}
}
